package com.generic.mybatis.dal.interceptor.automap.builder;

import com.generic.mybatis.dal.interceptor.automap.SqlBuilder;
import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import com.generic.mybatis.dal.interceptor.automap.TableMapperHolder;
import com.generic.mybatis.dal.util.OMPException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.Map;

import static com.generic.mybatis.dal.interceptor.automap.builder.SqlBuilderUtil.buildIdWhereStatement;

public class DeleteBuilder implements SqlBuilder {

    @Override
    public String buildSql(MappedStatement mappedStatement, Class dtoClass, Object object) throws Exception {
        if (null == object) {
            throw new OMPException("Sorry,I refuse to build sql for a null object!");
        }
        TableMapper tableMapper = TableMapperHolder.getTableMapper(dtoClass);
        Map dtoFieldMap = PropertyUtils.describe(object);
        SQL sql = new SQL().UPDATE(String.format("%s as %s", tableMapper.getTableName(), tableMapper.getAlias()));
        sql.SET("is_deleted = 'y',gmt_modified=now()");

        // delete from tableName where primaryKeyName=?
        buildIdWhereStatement(sql, tableMapper, dtoFieldMap);
        return sql.toString();
    }
}
